package com.suncaper.han_yi_system.filter;

import com.suncaper.han_yi_system.exception.CustomerException;
import com.suncaper.han_yi_system.handle.AuthenticationEntryPointImpl;
import com.suncaper.han_yi_system.pojo.entity.LoginUser;
import com.suncaper.han_yi_system.utils.JwtUtil;
import com.suncaper.han_yi_system.utils.RedisCache;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisCache redisCache;

    @Autowired
    AuthenticationEntryPointImpl authenticationException;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            //获取token
            String token = request.getHeader("token");
            if (!StringUtils.hasText(token)) {
                filterChain.doFilter(request, response);
                return;
            }

            //解析token
            String userId;
            try {
                Claims claims = JwtUtil.parseToken(token);
                userId = claims.get(JwtUtil.USER_INFO_ID).toString();
            } catch (Exception e) {
                throw new CustomerException(213,"token非法");
            }

            //从Redis中获取用户信息
            String redisKey = "login:" + userId;
            LoginUser loginUser = redisCache.getCacheObject(redisKey);

            if (loginUser == null) {
                throw new CustomerException(214,"token过期");
            }

            //存入SecurityContextHolder
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        } catch (Exception e) {
            log.error("登录校验失败:{}", e.getMessage());
            authenticationException.commence(request, response, null);
            return;
        }
        //放行
        filterChain.doFilter(request, response);

    }
}
